﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using TestProject.ModelClasses;


namespace TestProject
{
    public partial class Default : System.Web.UI.Page
    {

        private int _tableWidth;

        protected void Page_Load(object sender, EventArgs e)
        {
            using (NodesTree nodesTree = new NodesTree())
            {
                nodesTree.LoadFromDB();

                _tableWidth = nodesTree.Width;

                CreateTable(nodesTree.Width + 2, nodesTree.Height);

                int y = 0;

                FillTable(nodesTree.Nodes, 0, ref y);
                AddHeaders(nodesTree.Width);
            }

        }

        private void AddHeaders(int width)
        {
            TableRow row = new TableRow();

            TableCell classCell = new TableCell();
            classCell.Text = "Классификатор";
            classCell.ColumnSpan = width;

            TableCell idCell = new TableCell();
            idCell.Text = "Идентификатор";

            TableCell elementCell = new TableCell();
            elementCell.Text = "Элемент";

            classCell.CssClass = "HeaderCell";
            idCell.CssClass = "HeaderCell";
            elementCell.CssClass = "HeaderCell";

            row.Cells.Add(classCell);
            row.Cells.Add(idCell);
            row.Cells.Add(elementCell);

            tbClassifiries.Rows.AddAt(0, row);
             
        }


        private void CreateTable(int width, int height)
        {
            for (int y = 0; y < height; y++)
            {
                TableRow row = new TableRow();

                for (int x = 0; x < width; x++)
                {
                    TableCell cell = new TableCell();
                    row.Cells.Add(cell);
                }

                tbClassifiries.Rows.Add(row);
            }

        }



        private void FillTable(IEnumerable<Node> nodes, int x, ref int y)
        {
             foreach(Node node in nodes)
             {
                 tbClassifiries.Rows[y].Cells[x].Text = node.ToString();
                 //y++;

                 foreach (var pair in node.Pairs)
                 {
                     y++;

                     TableCell idCell = tbClassifiries.Rows[y].Cells[_tableWidth + 0];
                     TableCell elementCell = tbClassifiries.Rows[y].Cells[_tableWidth + 1];

                     idCell.Text = pair.Key.ToString();
                     elementCell.Text = pair.Element;

                     idCell.CssClass = elementCell.CssClass = "PairCell";

                 }
                 y++;

                 FillTable(node.ChildNodes, x + 1, ref y);
                
             }
        }

        



    }
}